from collections import deque
from decimal import Decimal
import heapq
from .order_book import OrderBook

class OrderBookSH(OrderBook):
    def __init__(self):
        super().__init__()

    # 获取当前竞价价格（集合竞价）
    def get_auction_price(self) -> tuple[Decimal | None, Decimal]:
        all_prices = sorted(set(self._buy_orders.keys()) | set(self._sell_orders.keys()))
        price_to_volume = dict()
        max_volume = Decimal("0")

        # 计算每个价格的成交量
        for price in all_prices:
            buy_qty = sum(
                order.rest_quantity()
                for p, orders in self._buy_orders.items()
                if p >= price
                for order in orders
            )
            sell_qty = sum(
                order.rest_quantity()
                for p, orders in self._sell_orders.items()
                if p <= price
                for order in orders
            )
            match_volume = min(buy_qty, sell_qty)
            price_to_volume[price] = match_volume
            if match_volume > max_volume:
                max_volume = match_volume

        # 找出所有最大成交量对应的价格
        candidate_prices = [p for p, v in price_to_volume.items() if v == max_volume]

        if not candidate_prices:
            return None, max_volume
        if len(candidate_prices) == 1:
            return candidate_prices[0], max_volume

        # 多个最大成交量的价格：取(min + max) / 2
        min_price = min(candidate_prices)
        max_price = max(candidate_prices)
        auction_price = (min_price + max_price) / Decimal("2")
        
        return auction_price, max_volume